package com.ybkj.o2o.zhuanxian.manager.impl;

import com.ybkj.o2o.zhuanxian.common.*;
import com.ybkj.o2o.zhuanxian.common.amqp.PushMessage;
import com.ybkj.o2o.zhuanxian.common.chart.ChartDay;
import com.ybkj.o2o.zhuanxian.common.chart.ChartMonth;
import com.ybkj.o2o.zhuanxian.common.chart.ChartYear;
import com.ybkj.o2o.zhuanxian.common.chart.HourChart;
import com.ybkj.o2o.zhuanxian.common.config.DaijiaApi;
import com.ybkj.o2o.zhuanxian.common.config.SalesApi;
import com.ybkj.o2o.zhuanxian.common.error.Error;
import com.ybkj.o2o.zhuanxian.common.error.ErrorConstantV4;
import com.ybkj.o2o.zhuanxian.entity.Car;
import com.ybkj.o2o.zhuanxian.entity.Line;
import com.ybkj.o2o.zhuanxian.entity.Order;
import com.ybkj.o2o.zhuanxian.entity.OrderMemo;
import com.ybkj.o2o.zhuanxian.entity.OrderRefuse;
import com.ybkj.o2o.zhuanxian.entity.OrderReview;
import com.ybkj.o2o.zhuanxian.entity.OrderStatus;
import com.ybkj.o2o.zhuanxian.manager.LineManager;
import com.ybkj.o2o.zhuanxian.manager.OrderManager;
import com.ybkj.o2o.zhuanxian.service.CarService;
import com.ybkj.o2o.zhuanxian.service.LineService;
import com.ybkj.o2o.zhuanxian.service.OrderMemoService;
import com.ybkj.o2o.zhuanxian.service.OrderRefuseService;
import com.ybkj.o2o.zhuanxian.service.OrderReviewService;
import com.ybkj.o2o.zhuanxian.service.OrderService;
import com.ybkj.o2o.zhuanxian.service.OrderStatusService;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.util.LangUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DefaultOrderManager implements OrderManager {
    private static final Logger logger = LoggerFactory.getLogger(DefaultOrderManager.class);

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderStatusService orderStatusService;
    @Autowired
    private CarService carService;
    @Autowired
    private OrderRefuseService orderRefuseService;
    @Autowired
    private LineService lineService;
    @Autowired
    private OrderReviewService orderReviewService;
    @Autowired
    private OrderMemoService orderMemoService;
    @Autowired
    private LineManager lineManager;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private SalesApi salesApi;
    @Autowired
    private DaijiaApi daijiaApi;

    @Override
    public void insertCycleRecord(Map<String,Object> map) {
        orderService.insertCycleRecord(map);
    }

    @Override
    public List<Map<String,Object>> redPacketCycle(Date orderDate, String cycle) {
        return orderService.redPacketCycle(orderDate, cycle);
    }

    @Override
    public List<Order> cycleOrder(Date startDate, Date endDate) {
        return orderService.cycleOrder(startDate, endDate);
    }

    @Override
    public Order insert(Integer orderType, Long lineId, String lineName, Long companyId,
                        String companyName, Long passengerId, String passengerName, String passengerPhone,
                        String channelName, String startAddress, Double startLat, Double startLng, String endAddress,
                        Double endLat, Double endLng, Date serverDate, Integer serverDeadTime, Double prestartPrice,
                        Double premileagePrice, Double prerunTimePrice, Double budgetPay, Long couponId,
                        Integer pretravelTime, Double premileage, Long peopleNumber, String operator, String memo,
                        String takeDeliveryName, String takeDeliveryPhone, String showPhone, String showName,
                        String appKey, Boolean system) {
        Order order = new Order();
        order.setOrderType(orderType);
        order.setLineId(lineId);
        order.setLineName(lineName);
        order.setCompanyId(companyId);
        order.setCompanyName(companyName);
        if (passengerId != null) {
            order.setPassengerId(passengerId);
        }
        order.setPassengerName(passengerName);
        order.setPassengerPhone(passengerPhone);
        order.setChannelName(channelName);
        order.setStartAddress(startAddress);
        order.setStartLat(startLat);
        order.setStartLng(startLng);
        order.setEndAddress(endAddress);
        order.setEndLat(endLat);
        order.setEndLng(endLng);
        order.setServerTime(serverDate);
        if (serverDeadTime != 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(serverDate);
            calendar.add(Calendar.MINUTE, -serverDeadTime);
            order.setServerDeadTime(calendar.getTime());
        }
        order.setPreStartPrice(prestartPrice);
        order.setPremileagePrice(premileagePrice);
        order.setPrerunTimePrice(prerunTimePrice);
        order.setBudgetPay(budgetPay);
        order.setPretravelTime(pretravelTime);
        order.setPremileage(premileage);
        order.setPeopleNumber(Order.TYPE_BAOCHE.equals(orderType) ? null : peopleNumber);
        order.setAppkey(appKey);
        order.setCouponId(couponId);
        order.setMemo(memo);
        order.setTreatment(false);
        order.setTakeDeliveryName(takeDeliveryName);
        order.setTakeDeliveryPhone(takeDeliveryPhone);
        order.setShowPhone(showPhone);
        order.setShowName(showName);

        //如果是app预约、微信公众号预约，则领取随机红包
        boolean isUserOwnOrder = false;
        if(Order.ORDER_TYPE_APP.equals(channelName) || Order.ORDER_TYPE_WEIXIN.equals(channelName) || Order.ORDER_TYPE_WEB.equals(channelName)){
            isUserOwnOrder = true;
        }
        //判断是否开起随机红包
        Object obj = daijiaApi.isRandomRedPacket("isRandomRedPacket");
        boolean isRandomRedPacket = Boolean.valueOf(obj.toString());
        if(isUserOwnOrder){
            if(isRandomRedPacket){
                Double randomRedPacket = redPacketProducer();
                order.setRandomRedPacket(randomRedPacket);
            }
//            Double randomRedPacket = new RandomRedPacket().redPacketProducer();
//            else {
//                order.setRandomRedPacket(new Double(0.0));
//            }
        }
        int is = orderService.insert(order);
        OrderStatus status = new OrderStatus();
        status.setOrderId(order.getId());
        status.setOperator(passengerName);
        status.setOrderNo(order.getOrderNo());
        status.setStatus(0);
        if (StringUtils.isNotBlank(operator) && "电话预约".equals(channelName)) {
            status.setMemo("管理员【" + operator + "】下单");
        } else {
            status.setMemo("客户【" + order.getPassengerName() + "】下单");
        }

        int jo = orderStatusService.insert(status);
        if (is != 1 || jo != 1) {
            throw new RuntimeException("下单失败!!");
        }
        if (couponId != null) {
            salesApi.updateV4(couponId, 2, appKey);
        }
        if (system == null || system == false) {
            try {
                PushMessage pushMessage = new PushMessage();
                pushMessage.setAppKey(appKey);
                pushMessage.setMessage("新单推送");
                pushMessage.setTargetId(order.getId());
                pushMessage.setPushType(PushMessage.PUSHTYPE_NEWORDER);
                pushMessage.setOrderType(PushMessage.ORDERTYPE_ZHUANXIAN);
                rabbitTemplate.convertAndSend(pushMessage);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return order;
    }

    /**
     * 判断是否生成最大红包
     */
    public Map<String,Object> isBiggestRedPacket(Date orderDate) {
        boolean isBiggestRedPacket = false;
        //获取周期类型
        Map<String,Object> redPacketMap = (Map)daijiaApi.isRandomRedPacket("cycle");
        String cycle = redPacketMap.get("cycle").toString();
        //查询周期记录
        List<Map<String,Object>> cycleList = orderService.redPacketCycle(orderDate, cycle);
        Map cycleRecord = cycleList.get(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //查询在周期开始时间和结束时间期间生成的订单信息
            List<Order> orderList = orderService.cycleOrder(sdf.parse(cycleRecord.get("startDate").toString()), sdf.parse(cycleRecord.get("endDate").toString()));
            //周期内是否已经生成最大金额红包
            boolean biggestRedPacket = false;
            for (Order order : orderList) {
                int status = order.getStatus();
                Double randomRedPacket = null == order.getRandomRedPacket() ? 0.0 : order.getRandomRedPacket();
                if (randomRedPacket > 5.0 && Order.ORDER_STATUS_XIAODAN != order.getStatus()) {
                    biggestRedPacket = true;
                    break;
                }
            }
            //是否满足生成最大红包的时间要求
            boolean isTime = false;
            Calendar ca = Calendar.getInstance();
            ca.setTime(orderDate);
            int redPacketDate = Integer.valueOf(cycleRecord.get("redPacketDate").toString());
            if (cycle.equals(RandomRedPacket.CYCLE_MONTH)) {
                int dayOfMonth = ca.get(Calendar.DATE);
                if (dayOfMonth == redPacketDate) {
                    isTime = true;
                }
            } else {
                int dayOfWeek = ca.get(Calendar.DAY_OF_WEEK);
                if (dayOfWeek == redPacketDate) {
                    isTime = true;
                }
            }
            if (isTime && !biggestRedPacket) isBiggestRedPacket = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("isBiggestRedPacket", isBiggestRedPacket);
        if (isBiggestRedPacket) {
            map.put("randomRedPacket", cycleRecord.get("randomRedPacket"));
        } else {
            map.put("randomRedPacket", 0.0);
        }
        return map;
    }

    /**
     * 红包生成器
     * 生成[x,y] x到y的随机小数
     */
    public Double redPacketProducer(){
        Double randomRedPacket = null;
        Map<String,Object> map = isBiggestRedPacket(new Date());
        //生成最大红包
        if(Boolean.valueOf(map.get("isBiggestRedPacket").toString())){
            randomRedPacket = Double.valueOf(map.get("randomRedPacket").toString());
        } else {
            Double[] section = RandomRedPacket.sectionSelector();
            Double x = section[0];
            Double y = section[1];
            Double d = y - Math.random() * (y - x);
            DecimalFormat df = new DecimalFormat("0.00");
            randomRedPacket = Double.valueOf(df.format(d));
        }
        return randomRedPacket;
    }

    /**
     * 已数据库为媒介更新order对象
     *
     * @param orderId
     * @param appKey
     * @return
     */
    @Override
    public Order findByIdAndAppKey(Long orderId, String appKey) {
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        if (order != null) {
            order.setOrderReview(orderReviewService.findByOrderIdAndAppKey(order.getId(), appKey));
            Line line = lineService.findById(order.getLineId(), appKey);
            if (line != null) {
                order.setLineName(line.getName());
                order.setAreaId(line.getAreaId());
            } else {
                order.setLineName("");
                order.setAreaId(null);
            }
            if (order.getCarId() != null) {
                Car car = carService.findOne(order.getCarId(), appKey);
                if (null != car) {
                    order.setCarName(car.getCarName());
                }
            }
            if (StringUtils.isBlank(order.getShowPhone())) {
                order.setShowPhone(order.getPassengerPhone());
            }
        }
        return order;
    }

    @Override
    public void baoxiao(Long orderId, Double baoxiaoMoney, String appKey) {
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        order.setBaoxiao(true);
        order.setBaoxiaoMoney(baoxiaoMoney);
        orderService.update(order);

    }

    @Override
    public int update(Order order) {

        return orderService.update(order);
    }

    @Override
    public List<Order> findOrderByEmployId(Long employId, Double money, String appKey,
                                           Long startTime, Long endTime) {
        return orderService.findOrderByEmployId(employId, money, appKey, startTime, endTime);
    }

    // 开始执行
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Error run(Long orderId, String operator, String appKey) {
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        if (order.getStatus() != 3) {
            return ErrorConstantV4.ORDER_STATUS_ERROR;
        }

        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(order.getId());
        orderStatus.setOrderNo(order.getOrderNo());
        orderStatus.setOperator(order.getEmployName());
        orderStatus.setStatus(4);
        orderStatus.setMemo("服务人员【" + order.getEmployName() + "】" + "开始执行订单");

        order.setUpdated(new Date());
        order.setStatus(4);

        int is = orderStatusService.insert(orderStatus);
        int jo = orderService.updateIngoreNull(order);
        if (is != 1 || jo != 1) {
            throw new RuntimeException("出发失败");
        }
        try {
            PushMessage pushMessage = new PushMessage();
            pushMessage.setAppKey(appKey);
            pushMessage.setMessage("开始执行订单");
            pushMessage.setEmployId(order.getEmployId());
            pushMessage.setTargetId(order.getId());
            pushMessage.setPushType(PushMessage.PUSHTYPE_RUN);
            pushMessage.setOrderType(PushMessage.ORDERTYPE_ZHUANXIAN);
            rabbitTemplate.convertAndSend(pushMessage);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ErrorConstantV4.SUCCESS;
    }

    // 到达预约地,开始等待
    @Override
    public Error wait(Long orderId, String operator, String appKey) {
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        if (order.getStatus() != 2) {
            System.out.println("订单状态错误" + order.getStatus());
            return ErrorConstantV4.ORDER_STATUS_ERROR;
        }

        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(order.getId());
        orderStatus.setOrderNo(order.getOrderNo());
        orderStatus.setOperator(operator);
        orderStatus.setStatus(3);
        orderStatus.setMemo("服务人员【" + order.getEmployName() + "】" + "到达预约地");

        order.setUpdated(new Date());
        order.setStatus(3);

        int is = orderStatusService.insert(orderStatus);
        int jo = orderService.updateIngoreNull(order);
        if (is != 1 || jo != 1) {
            throw new RuntimeException("等待失败");
        }
        try {
            PushMessage pushMessage = new PushMessage();
            pushMessage.setAppKey(appKey);
            pushMessage.setMessage("到达预约地,开始等待");
            pushMessage.setEmployId(order.getEmployId());
            pushMessage.setTargetId(order.getId());
            pushMessage.setPushType(PushMessage.PUSHTYPE_ARRIVE);
            pushMessage.setOrderType(PushMessage.ORDERTYPE_ZHUANXIAN);
            rabbitTemplate.convertAndSend(pushMessage);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ErrorConstantV4.SUCCESS;
    }

    // 拒单
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Error refuse(Long orderId, Long employId, String cause, String operator, String appKey) {
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        if (order.getStatus() != 1) {
            return ErrorConstantV4.ORDER_STATUS_ERROR;
        }
        order.setUpdated(new Date());

        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(order.getId());
        orderStatus.setOrderNo(order.getOrderNo());
        orderStatus.setOperator(operator);
        orderStatus.setStatus(0);
        orderStatus.setMemo("服务人员【" + order.getEmployName() + "】" + "拒绝执行订单");
        OrderRefuse orderRefuse = new OrderRefuse();
        orderRefuse.setEmployId(order.getEmployId());
        orderRefuse.setEmployName(order.getEmployName());
        orderRefuse.setEmployPhone(order.getEmployPhone());
        orderRefuse.setOrderId(order.getId());
        orderRefuse.setOrderNo(order.getOrderNo());
        orderRefuse.setPassengerId(order.getPassengerId());
        orderRefuse.setPassengerName(order.getPassengerName());
        orderRefuse.setPassengerPhone(order.getPassengerPhone());
        orderRefuse.setMemo(cause);
        orderRefuse.setAppKey(order.getAppkey());
        orderRefuse.setCompanyId(order.getCompanyId());
        orderRefuse.setCompanyName(order.getCompanyName());
        order.setStatus(0);
        Car car = carService.findByEmploy(order.getEmployId(), appKey);
        if (null != car) {
            car.setStatus(Car.CAR_FREE);
            carService.update(car);
        }
        order.setEmployId(null);
        order.setEmployName(null);
        order.setEmployPhone(null);
        order.setEmployNo(null);
        order.setEmployPhoto(null);
        order.setEmployScore(null);
        order.setEmployCompanyId(null);
        order.setCarNumber(null);
        int is = orderStatusService.insert(orderStatus);
        int jo = orderService.update(order);
        int rs = orderRefuseService.insert(orderRefuse);
        if (rs != 1 || is != 1 || jo != 1) {
            throw new RuntimeException("拒单失败");
        }
        try {
            PushMessage pushMessage = new PushMessage();
            pushMessage.setAppKey(appKey);
            pushMessage.setMessage(cause);
            pushMessage.setEmployId(orderRefuse.getEmployId());
            pushMessage.setTargetId(order.getId());
            pushMessage.setPushType(PushMessage.PUSHTYPE_REFUSE);
            pushMessage.setOrderType(PushMessage.ORDERTYPE_ZHUANXIAN);
            rabbitTemplate.convertAndSend(pushMessage);
        } catch (Exception ex) {
            ex.printStackTrace();
        }


        return ErrorConstantV4.SUCCESS;
    }

    // 抢单
    @Override
    public Order grab(Long orderId, Long employId, String employName, String employPhone,
                      String employNo, Double employScore, String employPhoto,
                      Long employCompanyId, String appKey) {

        Car car = carService.findByEmploy(employId, appKey);
        if (car == null) {
            throw new RuntimeException("抢单的司机没有车辆");
        }
        car.setStatus(Car.CAR_FREE);
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        carService.update(car);
        order.setCarNumber(car.getCarNumber());
        order.setCarId(car.getId());
        order.setCarName(car.getCarName());
        order.setEmployId(employId);
        order.setEmployName(employName);
        order.setEmployPhone(employPhone);
        order.setEmployNo(employNo);
        order.setEmployScore(employScore);
        order.setEmployPhoto(employPhoto);
        order.setEmployCompanyId(employCompanyId);
        order.setUpdated(new Date());
        order.setStatus(2);
        OrderStatus status = new OrderStatus();
        status.setOrderId(order.getId());
        status.setOrderNo(order.getOrderNo());
        status.setStatus(2);
        status.setOperator(employName);
        status.setMemo("【" + employName + "】" + "抢单成功");
        orderStatusService.insert(status);
        orderService.update(order);
        try {
            PushMessage pushMessage = new PushMessage();
            pushMessage.setAppKey(appKey);
            pushMessage.setMessage("服务人员接单");
            pushMessage.setEmployId(order.getEmployId());
            pushMessage.setTargetId(order.getId());
            pushMessage.setPushType(PushMessage.PUSHTYPE_ACCEPT);
            pushMessage.setOrderType(PushMessage.ORDERTYPE_ZHUANXIAN);
            rabbitTemplate.convertAndSend(pushMessage);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return orderService.findByIdAndAppKey(orderId, appKey);
    }

    // 接单
    @Override
    public Error jiedan(Long orderId, String appKey) {
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        if (order.getStatus() != 1) {
            return ErrorConstantV4.ORDER_STATUS_ERROR;
        }
        order.setUpdated(new Date());
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(order.getId());
        orderStatus.setOrderNo(order.getOrderNo());
        orderStatus.setOperator(order.getEmployName());

        orderStatus.setStatus(Order.ORDER_STATUS_JIEDAN);
        orderStatus.setOperator(order.getEmployName());
        orderStatus.setMemo("【" + order.getEmployName() + "】" + "接单成功");
        order.setStatus(Order.ORDER_STATUS_JIEDAN);

        int is = orderStatusService.insert(orderStatus);

        int jo = orderService.updateIngoreNull(order);
        if (is != 1 || jo != 1) {
            throw new RuntimeException("接单失败");
        }
        try {
            String result = daijiaApi.jiedanSms(appKey, order);
            PushMessage pushMessage = new PushMessage();
            pushMessage.setAppKey(appKey);
            pushMessage.setMessage("服务人员接单");
            pushMessage.setEmployId(order.getEmployId());
            pushMessage.setTargetId(order.getId());
            pushMessage.setPushType(PushMessage.PUSHTYPE_ACCEPT);
            pushMessage.setOrderType(PushMessage.ORDERTYPE_ZHUANXIAN);
            rabbitTemplate.convertAndSend(pushMessage);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ErrorConstantV4.SUCCESS;
    }

    @Override
    public DataGrid<Order> findByParam(Long startTime, Long endTime, Long companyId,
                                       String companyName, String orderNo, Long passengerId, String passengerName,
                                       String passengerPhone, Long employId, String employName, String employPhone,
                                       String carNumber, String orderby, String allorderType, String allstatus, Integer page,
                                       Integer rows, Boolean treatment, Long startFinishTime, Long endFinishTime, Long lineId,
                                       String appKey, Long[] linesId) {
        Integer offset = null;
        if (page != null && rows != null) {
            offset = (page - 1) * rows;
        }
        Date start = null;
        if (startTime != null) {
            start = new Date(startTime);
        }
        Date end = null;
        if (endTime != null) {
            end = new Date(endTime);
        }
        Date startFinish = null;
        if (startFinishTime != null) {
            startFinish = new Date(startFinishTime);
        }
        Date endFinish = null;
        if (endFinishTime != null) {
            endFinish = new Date(endFinishTime);
        }
        List<String> orderTypes = null;
        if (StringUtils.isNotBlank(allorderType)) {
            orderTypes = new ArrayList<String>();
            String[] split = allorderType.split(",");
            for (int i = 0; i < split.length; i++) {
                String si = split[i];
                if (si != null) {
                    orderTypes.add(si);
                }
            }
        }
        List<Integer> statuss = new ArrayList<Integer>();
        if (StringUtils.isNotBlank(allstatus)) {
            if (treatment != null && treatment && !allstatus.contains("4")) {
                allstatus += ",4";
            }
            String[] split = allstatus.split(",");
            for (int i = 0; i < split.length; i++) {
                String si = split[i];
                if (si != null) {
                    statuss.add(Integer.valueOf(si));
                }
            }
        }
        List<Order> list =
                orderService.findByParam(start, end, companyId, companyName, orderNo, passengerId,
                        passengerName, passengerPhone, employId, employName, employPhone, carNumber, orderby,
                        orderTypes, statuss, rows, offset, treatment, startFinish, endFinish, lineId, appKey, linesId);
        for (Order order : list) {
            Line line = lineService.findById(order.getLineId(), appKey);
            if (line != null) {
                order.setLineName(line.getName());
                order.setAreaId(line.getAreaId());
            } else {
                order.setAreaId(null);
            }
            if (order.getCarId() != null) {
                Car car = carService.findOne(order.getCarId(), appKey);
                if (null != car) {
                    order.setCarName(car.getCarName());
                }
            }
            List<OrderMemo> orderMemos = orderMemoService.findByOrderId(order.getId());
            order.setOrderMemos(orderMemos);
            OrderReview orderReview = orderReviewService.findByOrderIdAndAppKey(order.getId(), appKey);
            order.setOrderReview(orderReview);
        }
        Long count =
                orderService.countByParam(start, end, companyId, companyName, orderNo, passengerId,
                        passengerName, passengerPhone, employId, employName, employPhone, carNumber, orderby,
                        orderTypes, statuss, treatment, startFinish, endFinish, lineId, appKey, linesId);
        DataGrid<Order> dataGrid = new DataGrid<Order>();
        dataGrid.setRows(list);
        dataGrid.setTotal(count);

        return dataGrid;
    }

    /**
     * .
     */
    @Transactional
    public void paidan(Order order, Car car, Long employId, String employName, String employPhone,
                       Long employCompanyId, String employNo, String employPhoto, Double employScore,
                       String operator, String operatorMemo, String appKey) {
        order.setUpdated(new Date());
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(order.getId());
        orderStatus.setOrderNo(order.getOrderNo());
        orderStatus.setOperator(operator);
        orderStatus.setStatus(1);
        order.setCarId(car.getId());
        order.setCarNumber(car.getCarNumber());
        order.setCarName(car.getCarName());
        car.setStatus(1);
        carService.update(car);
        order.setEmployId(employId);
        order.setEmployName(employName);
        order.setEmployPhone(employPhone);
        order.setEmployCompanyId(employCompanyId);
        order.setEmployNo(employNo);
        order.setEmployPhoto(employPhoto);
        order.setEmployScore(employScore);
        orderStatus.setMemo(operatorMemo);
        order.setStatus(Order.ORDER_STATUS_PAIDAN);
        orderService.update(order);
        orderStatusService.insert(orderStatus);
    }


    @Override
    public Long countFinishByPassenger(Long passengerId, Date startTime, Date endTime, String appKey,
                                       String orderFromSources) {
        List<String> channelNames = new LinkedList<String>();
        if (StringUtils.isNotBlank(orderFromSources)) {
            String[] strs = orderFromSources.split(",");
            for (String str : strs) {
                channelNames.add(str);
            }
        }

        return orderService.countFinishByPassenger(passengerId, startTime, endTime, appKey,
                channelNames);
    }

    // 司机补单
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order addmore(Integer orderType, Long passengerId, String passengerName,
                         String passengerPhone, Long companyId, String companyName, String channelName,
                         String startAddress, Double startLat, Double startLng, String endAddress, Double endLat,
                         Double endLng, Date serverDate, Integer serverDeadTime, Long employId, String employName,
                         String employPhone, Long employCompanyId, String employNo, String employPhoto,
                         Double employScore, Long peopleNumber, String memo, Double budgetPay,
                         String takeDeliveryName, String takeDeliveryPhone, String appKey) {
        Order order = new Order();
        order.setOrderType(orderType);
        order.setPassengerId(passengerId);
        order.setPassengerName(passengerName);
        order.setPassengerPhone(passengerPhone);
        order.setShowPhone(passengerPhone);
        order.setCompanyId(companyId);
        order.setCompanyName(companyName);
        Car car = carService.findByEmploy(employId, appKey);

        List<Line> line = lineManager.findByCar(car.getId(), appKey);
        if (line == null || line.size() == 0) {
            throw new RuntimeException("该服务人员没有所属路线");
        }
        order.setCarId(car.getId());
        order.setCarName(car.getCarName());
        order.setCarNumber(car.getCarNumber());
        order.setLineId(line.get(0).getId());
        order.setLineName(line.get(0).getName());
        order.setChannelName(channelName);
        order.setStartAddress(startAddress);
        order.setStartLat(startLat);
        order.setStartLng(startLng);
        order.setServerTime(serverDate);
        if (serverDeadTime != 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(serverDate);
            calendar.add(Calendar.MINUTE, -serverDeadTime);
            order.setServerDeadTime(calendar.getTime());
        }
        order.setEndAddress(endAddress);
        order.setEndLat(endLat);
        order.setEndLng(endLng);
        order.setEmployId(employId);
        order.setEmployName(employName);
        order.setEmployPhone(employPhone);
        order.setEmployCompanyId(employCompanyId);
        order.setEmployNo(employNo);
        order.setEmployPhoto(employPhoto);
        order.setEmployScore(employScore);
        order.setPeopleNumber(Order.TYPE_BAOCHE.equals(orderType) ? null : peopleNumber);
        order.setAppkey(appKey);
        order.setBudgetPay(budgetPay);
        if (takeDeliveryName != null) {
            order.setTakeDeliveryName(takeDeliveryName);
        } else {
            order.setTakeDeliveryName(order.getPassengerName());
        }
        if (takeDeliveryPhone != null) {
            order.setTakeDeliveryPhone(takeDeliveryPhone);
        } else {
            order.setTakeDeliveryPhone(order.getPassengerPhone());
        }
        order.setStatus(Order.ORDER_STATUS_JIEDAN);
        int is = orderService.addmore(order);
        if (is != 1) {
            throw new RuntimeException("补单失败!!");
        }
        // 保存下单状态记录
        OrderStatus status = new OrderStatus();
        status.setOrderId(order.getId());
        status.setOperator(employName);
        status.setOrderNo(order.getOrderNo());
        status.setStatus(0);
        status.setMemo("服务人员【" + employName + "】补单");
        int jo = 0;
        jo = orderStatusService.insert(status);
        // 保存派单状态记录
        status.setOrderId(order.getId());
        status.setOperator(employName);
        status.setOrderNo(order.getOrderNo());
        status.setStatus(1);
        status.setMemo("【" + employName + "】派单成功");
        jo = orderStatusService.insert(status);
        // 保存接单状态记录
        status.setOrderId(order.getId());
        status.setOperator(employName);
        status.setOrderNo(order.getOrderNo());
        status.setStatus(2);
        status.setMemo("【" + employName + "】接单成功");
        jo = orderStatusService.insert(status);
        if (StringUtils.isNotBlank(memo)) {
            OrderMemo orderMemo = new OrderMemo();
            orderMemo.setMemo(memo);
            orderMemo.setOperator(employName);
            orderMemo.setOrderId(order.getId());
            orderMemo.setOrderNo(order.getOrderNo());
            orderMemoService.insert(orderMemo);
        }
        try {
            Car cars = carService.findByEmploy(employId, appKey);
            cars.setStatus(Car.CAR_BUSY);// 补单后把车辆设置为忙碌状态
            carService.update(cars);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        String smsResult = daijiaApi.jiedanSms(appKey,order);
        try {
            PushMessage pushMessage = new PushMessage();
            pushMessage.setAppKey(appKey);
            pushMessage.setMessage("服务人员补单");
            pushMessage.setTargetId(order.getId());
            pushMessage.setEmployId(order.getEmployId());
            pushMessage.setPushType(PushMessage.PUSHTYPE_BUDAN);
            pushMessage.setOrderType(PushMessage.ORDERTYPE_ZHUANXIAN);
            pushMessage.setFrom(PushMessage.FROM_EMPLOY);
            rabbitTemplate.convertAndSend(pushMessage);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return order;
    }

    // 收回
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int callback(Long orderId, String operator, String cause, String appKey) {
        System.out.println("DefaultOrderManager.updateStatus()");
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        int jo = 0;
        if (order != null) {
            order.setUpdated(new Date());
            order.setEmployId(null);
            order.setEmployName(null);
            order.setEmployPhone(null);
            order.setEmployNo(null);
            order.setEmployPhoto(null);
            order.setEmployScore(null);
            order.setEmployCompanyId(null);
            order.setCarNumber(null);
            OrderStatus orderStatus = new OrderStatus();
            orderStatus.setOrderId(order.getId());
            orderStatus.setOrderNo(order.getOrderNo());
            orderStatus.setOperator(operator);
            String message = "";
            message = "收回订单失败";
            order.setStatus(0);
            Car car = carService.findByEmploy(order.getEmployId(), appKey);
            if (car != null) {
                car.setStatus(Car.CAR_FREE);
                carService.update(car);
            }
            orderStatus.setOperator(operator);
            orderStatus.setStatus(0);
            orderStatus.setMemo("管理员【" + operator + "】" + "强行收回订单");
            jo = orderService.update(order);
            orderStatusService.insert(orderStatus);
        }
        return jo;
    }

    // 司机销单
    @Override
    public int employCancel(Long orderId, Long employId, String employName, String employPhone,
                            Long employCompanyId, String employNo, String employPhoto, Double employScore, String cause,
                            String appKey) {
        System.out.println("DefaultOrderManager.updateStatus()");
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        int jo = 0;
        if (order != null) {
            order.setUpdated(new Date());
            OrderStatus orderStatus = new OrderStatus();
            orderStatus.setOrderId(order.getId());
            orderStatus.setOrderNo(order.getOrderNo());
            orderStatus.setOperator(order.getEmployName());
            String message = "";
            boolean bl = false;
            message = "销单失败";
            if (order.getStatus() < 4) {
                if (null != order.getEmployId()) {
                    Car car = carService.findByEmploy(order.getEmployId(), appKey);
                    if (car != null) {
                        car.setStatus(Car.CAR_FREE);
                        carService.update(car);
                    }
                }
                orderStatus.setStatus(6);
                orderStatus.setMemo("服务人员【" + order.getEmployName() + "】" + "取消订单");
                order.setStatus(6);
                order.setIsClosed(true);
                order.setCancelCause(cause);
            } else {
                message = "订单已销单或已出发,不能销单";
                bl = true;
            }
            if (bl) {
                throw new RuntimeException(message);
            }
            System.out.println("DefaultOrderManager.updateStatus()");
            jo = orderService.update(order);
            orderStatusService.insert(orderStatus);
            try {
                PushMessage pushMessage = new PushMessage();
                pushMessage.setAppKey(appKey);
                pushMessage.setMessage("服务人员销单");
                pushMessage.setTargetId(order.getId());
                pushMessage.setEmployId(order.getEmployId());
                pushMessage.setPushType(PushMessage.PUSHTYPE_CANCEL);
                pushMessage.setOrderType(PushMessage.ORDERTYPE_ZHUANXIAN);
                pushMessage.setFrom(PushMessage.FROM_EMPLOY);
                rabbitTemplate.convertAndSend(pushMessage);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return jo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int passengerCancel(Long orderId, Long passengerId, String passengerName,
                               String passengerPhone, String cause, String appKey) {
        System.out.println("DefaultOrderManager.updateStatus()");
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        int jo = 0;
        if (order != null) {
            order.setUpdated(new Date());
            OrderStatus orderStatus = new OrderStatus();
            orderStatus.setOrderId(order.getId());
            orderStatus.setOrderNo(order.getOrderNo());
            orderStatus.setOperator(order.getPassengerName());
            String message = "";
            boolean bl = false;
            message = "销单失败";
            if (order.getStatus() < 4) {
                orderStatus.setStatus(6);
                orderStatus.setMemo("客户【" + order.getPassengerName() + "】" + "取消订单");
                order.setStatus(6);
                order.setIsClosed(true);
                order.setCancelCause(cause);
            } else {
                message = "订单已销单或已出发,不能销单";
                bl = true;
            }
            if (bl) {
                throw new RuntimeException(message);
            }
            jo = orderService.update(order);
            orderStatusService.insert(orderStatus);
            //取消订单，修改订单绑定的优惠券的状态为“未使用”
            Long orderCouponId = order.getCouponId();
            //如果订单绑定了优惠券，消单修改优惠券状态
            if(null != orderCouponId){
                salesApi.updateV4(order.getCouponId(),1,appKey);
            }
            try {
                PushMessage pushMessage = new PushMessage();
                pushMessage.setAppKey(appKey);
                pushMessage.setMessage("客户销单");
                pushMessage.setTargetId(order.getId());
                pushMessage.setEmployId(order.getEmployId());
                pushMessage.setPushType(PushMessage.PUSHTYPE_CANCEL);
                pushMessage.setOrderType(PushMessage.ORDERTYPE_ZHUANXIAN);
                pushMessage.setFrom(PushMessage.FROM_PASSENGER);
                rabbitTemplate.convertAndSend(pushMessage);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return jo;
    }

    // 确认订单结算信息
    @Override
    public Order complete(Long orderId, Double realPay, Double guoluMoney, Double yuanchengMoney,
                          Double otherMoney, Double startPrice, Double mileagePrice, Double runTimePrice,
                          Integer waitTime, Double waitPrice, String endAddress, Double endLat, Double endLng,
                          Double mileage, Integer runTime, Double couponMoney, String appKey, String prePayTypeDetail,
                          String memo, Double justKilometres, BigDecimal justMoney) {
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        order.setTreatment(true);
        order.setTreatmentDate(new Date());
        if (guoluMoney != null && guoluMoney != 0) {
            order.setGuoluMoney(guoluMoney);
        }
        if (yuanchengMoney != null && yuanchengMoney != 0) {
            order.setYuanchengMoney(yuanchengMoney);
        }
        if (otherMoney != null && otherMoney != 0) {
            order.setOtherMoney(otherMoney);
        }
        if (realPay != null) {
            order.setRealPay(realPay);
        }
        if (startPrice != null) {
            order.setStartPrice(startPrice);
        }
        if (mileagePrice != null) {
            order.setMileagePrice(mileagePrice);
        }
        if (runTimePrice != null) {
            order.setRunTimePrice(runTimePrice);
        }
        if (waitPrice != null) {
            order.setWaitPrice(waitPrice);
        }
        if (mileage != null) {
            order.setMileage(mileage);
        }
        if (runTime != null) {
            order.setRunTime(runTime);
        }
        if (couponMoney != null) {
            order.setCouponMoney(couponMoney);
        }
        if (StringUtils.isNotBlank(endAddress)) {
            order.setEndAddress(endAddress);
            order.setEndLat(endLat);
            order.setEndLng(endLng);
        }
        if (StringUtils.isNotBlank(prePayTypeDetail)) {
            order.setPrePayTypeDetail(prePayTypeDetail);
        }
        if (StringUtils.isNotBlank(memo)) {
            order.setEmployMemo(memo);
        }
        if (justKilometres != null) {
            order.setJustKilometres(justKilometres);
        }
        if (justMoney != null) {
            order.setJustMoney(justMoney);
        }
        order.setStartWait(waitTime);
        orderService.updateIngoreNull(order);
        if (order.getCarId() != null) {
            Car car = carService.findOne(order.getCarId(), appKey);
            if (null != car) {
                car.setStatus(Car.CAR_FREE);
                carService.update(car);
            }
        }
        return order;
    }

    @Override
    public Order findLastOrder(Long passengerId, String appKey) {
        List<Order> list = orderService.findMyFinishOrder(passengerId, appKey);

        if (list != null && list.size() != 0) {
            Long orderId = null;
            Order order = list.get(list.size() - 1);
            orderId = order.getId();
            List<OrderStatus> statusList = orderStatusService.findByOrderId(orderId);
            if (statusList != null && statusList.size() != 0) {
                OrderStatus status = statusList.get(statusList.size() - 1);
                Date finishTime = status.getCreated();
                order.setFinishTime(finishTime);
                return order;
            }
        }
        return null;
    }

    @Override
    public Order finishTask(Long orderId, String afterPayTypeDetail, Double companyProfit,
                            Double employProfit, Double signMoney, Double balanceMoney, Double alipayMoney,
                            Double weixinMoney, Double unionpayMoney, Double cashMoney, String appKey) {
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        if (StringUtils.isNotBlank(afterPayTypeDetail)) {
            // 后支付类型 cashMoney(代付) sign(签单) balance(余额) alipay(支付宝) weixin(微信)
            order.setAfterPayTypeDetail(afterPayTypeDetail);
        }
        order.setSignMoney(signMoney);
        order.setBalanceMoney(balanceMoney);
        order.setAlipayMoney(alipayMoney);
        order.setWeixinMoney(weixinMoney);
        order.setUnionpayMoney(unionpayMoney);
        order.setCashMoney(cashMoney);
        order.setCompanyProfit(companyProfit);
        order.setEmployProfit(employProfit);
        order.setStatus(5);
        order.setFinishTime(new Date());
        OrderStatus status = new OrderStatus();
        status.setOrderId(order.getId());
        status.setOrderNo(order.getOrderNo());
        status.setStatus(5);
        status.setOperator(order.getPassengerName());
        status.setMemo("服务人员【" + order.getEmployName() + "】"
                + "到达目的地,并且结算完成,行驶时间为：" + order.getRunTime() + "分钟   行驶里程为："
                + order.getMileage() + "公里");
        orderStatusService.insert(status);

        orderService.updateIngoreNull(order);
        return order;
    }

    @Override
    public ChartYear dataForYear(Integer year, Long companyId, String appKey) {
        ChartYear chartYear = orderService.dataForYear(year, companyId, appKey);
        return chartYear;
    }

    @Override
    public ChartMonth dataForMonth(Integer year, Long companyId, Integer month, String appKey) {
        ChartMonth chartMonth = orderService.dataForMonth(year, month, companyId, appKey);
        List<ChartDay> lists = new ArrayList<ChartDay>();
        for (int i = 1; i <= chartMonth.getDays(); i++) {
            lists.add(orderService.dataForChartDay(year, month, i, companyId, appKey));
        }
        chartMonth.setChartDays(lists);
        return chartMonth;
    }

    @Override
    public ChartDay dataForDay(Integer year, Integer month, Integer day, Long companyId,
                               String appKey) {
        ChartDay chartDay = orderService.dataForChartDay(year, month, day, companyId, appKey);
        List<HourChart> hours = new ArrayList<HourChart>();
        for (int i = 0; i < 24; i++) {
            hours.add(orderService.dataForhour(year, month, day, i, companyId, appKey));
        }
        chartDay.setHours(hours);
        return chartDay;
    }

    @Override
    public Order findFinishedByDriverWithDate(Long employId, Date start, Date end, String appKey) {
        return orderService.findByDriverAndFinishTime(employId, start, end, appKey);
    }

    @Override
    public List<Order> findMonthOrder(Integer year, Integer month, String appKey) {
        return orderService.findMonthOrder(year, month, appKey);
    }

    @Override
    public PageVo<MemberOrderVo> findMemberOrder(Date startTime, Date endTime, Long companyId,
                                                 String appKey) {
        return orderService.findMemberOrder(startTime, endTime, companyId, appKey);
    }

    @Override
    public PageVo<OrderFromSourceVo> orderFromSource(Date date1, Date date2, Long companyId,
                                                     String appKey) {
        PageVo<OrderFromSourceVo> source =
                orderService.orderFromSource(date1, date2, companyId, appKey);
        return source;
    }

    @Override
    public PageVo<DriverOrderVo> driverAchievement(Date date1, Date date2, Long empCompanyId,
                                                   String appKey) {
        PageVo<DriverOrderVo> source =
                orderService.driverAchievement(date1, date2, empCompanyId, appKey);
        return source;
    }

    @Override
    public PageVo<CompanyOrderVo> companyOrder(Date date1, Date date2, String appKey) {
        PageVo<CompanyOrderVo> source = orderService.companyOrder(date1, date2, appKey);
        return source;
    }

    @Override
    public PageVo<DriverOrderDetailVo> driverOrderDetailVo(Long driverId, Date start, Date end,
                                                           Integer page, Integer rows, String appKey) {
        PageVo<DriverOrderDetailVo> pageVo = orderService.driverOrderDetailVo(
                driverId, start, end, page, rows, appKey);
        return pageVo;
    }

    @Override
    public Map<String, Object> chart(Long companyId, Date startTime, Date endTime,
                                     Boolean maincompany, Long lineId, String appKey) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Integer> status = new ArrayList<Integer>();
        status.add(5);
        List<Order> list2 =
                orderService.findByParam(null, null, null, null, null, null, null, null, null, null, null,
                        null, null, null, status, null, null, null, startTime, endTime, lineId, appKey, null);
        status.clear();
        status.add(0);
        status.add(1);
        status.add(2);
        status.add(3);
        status.add(4);
        status.add(6);
        List<Order> list =
                orderService.findByParam(startTime, endTime, null, null, null, null, null, null, null,
                        null, null, null, null, null, status, null, null, null, null, null, lineId, appKey, null);
        try {
            int orderNumber = 0;// 自己公司司机完成的订单数量
            int runOrderNumber = 0;// 自己公司司机执行中的订单数量
            int otherOrderNumber = 0;// 其他公司司机完成的订单数量
            int runOtherOrderNumber = 0;// 其他公司司机执行中的订单数量
            int cancelOrderNumber = 0;// 自己公司销单的订单数量
            int inOrderNumber = 0;// 其他公司创建的订单本公司司机完成的订单数量
            int inRunOrderNumber = 0;// 其他公司创建的订单本公司司机正在执行的订单数量

            Double orderRealCash = 0.0;// 本公司创建由本公司司机完成的订单金额
            Double otherOrderRealCash = 0.0;// 本公司创建由其他公司司机完成的订单金额
            Double inOrderRealCash = 0.0;// 其他公司创建由本公司司机完成的订单金额

            Double companyProfit = 0.0;// 公司收入
            Double otherCompanyProfit = 0.0;// 本公司创建由其他公司司机完成的收入
            Double inCompanyProfit = 0.0;// 其他公司创建由本公司司机完成的收入

            Double driverProfit = 0.0;// 司机收入
            Double otherDriverProfit = 0.0;// 其他公司的司机完成的收入
            Double inDriverProfit = 0.0;// 其他公司创建订单由本公司的司机完成的收入


            Double orderFinishedCouponMoneyThis = 0.0;// 由本公司司机完成订单优惠券金额;
            Double orderFinishedCouponMoneyGetout = 0.0;// 由平台其它公司司机完成订单优惠券金额;
            Double orderFinishedCouponMoneyComein = 0.0;
            //平台其它公司创建、由本公司司机完成的订单优惠券金额;
            Double totalGuoluMoney = 0.0;// 所有过路费
            int totalAmount = 0;// 所有公司单量
            int totalCancelAmount = 0;// 所有公司销单量
            Double totalRealCash = 0.0;// 所有公司订单金额
            Double totalPayMoney = 0.0; // 所有支付金额
            Double totalCompanyProfit = 0.0;// 所有公司收入
            Double totalDriverProfit = 0.0;// 所有司机收入
            if (list2 != null && list2.size() != 0) {
                for (int i = 0; i < list2.size(); i++) {
                    Order order = list2.get(i);
                    if (companyId.equals(order.getCompanyId())) {
                        // 本公司创建的订单
                        if (order.getStatus() == 5
                                && order.getCompanyId().equals(order.getEmployCompanyId())) {
                            // 完成的订单
                            orderNumber++;
                            orderRealCash += order.getRealPay() != null ? order.getRealPay() : 0.0;
                            companyProfit += order.getCompanyProfit() != null ? order.getCompanyProfit() : 0.0;
                            driverProfit += order.getEmployProfit() != null ? order.getEmployProfit() : 0.0;
                            orderFinishedCouponMoneyThis +=
                                    order.getCouponMoney() != null ? order.getCouponMoney() : 0.0;
                        }
                        // 外派订单
                        if (order.getStatus() == 5
                                && !order.getCompanyId().equals(order.getEmployCompanyId())) {
                            otherOrderNumber++;
                            otherOrderRealCash += order.getRealPay() != null ? order.getRealPay() : 0.0;
                            otherCompanyProfit +=
                                    order.getCompanyProfit() != null ? order.getCompanyProfit() : 0.0;
                            otherDriverProfit = order.getEmployProfit() != null ? order.getEmployProfit() : 0.0;
                            orderFinishedCouponMoneyGetout +=
                                    order.getCouponMoney() != null ? order.getCouponMoney() : 0.0;
                        }
                    } else {
                        // 调入订单
                        if (order.getStatus() == 5 && companyId.equals(order.getEmployCompanyId())) {
                            inOrderNumber++;
                            inOrderRealCash += order.getRealPay() != null ? order.getRealPay() : 0.0;
                            inCompanyProfit += order.getCompanyProfit() != null ? order.getCompanyProfit() : 0.0;
                            inDriverProfit += order.getEmployProfit() != null ? order.getEmployProfit() : 0.0;
                            orderFinishedCouponMoneyComein +=
                                    order.getCouponMoney() != null ? order.getCouponMoney() : 0.0;
                        }
                    }

                }
            }


            if (list != null && list.size() != 0) {
                for (int i = 0; i < list.size(); i++) {
                    Order order = list.get(i);
                    if (order.getStatus() == 6) {
                        totalCancelAmount++;
                    }
                    if (companyId.equals(order.getCompanyId())) {
                        // 本公司创建的订单
                        /*
                         * if(order.getStatus()==5 && order.getCompanyId()==order.getEmployCompanyId()){
                         * //完成的订单
                         * orderNumber++; orderRealCash+=order.getRealPay()!=null?order.getRealPay():0.0;
                         * companyProfit+=order.getCompanyProfit()!=null?order.getCompanyProfit():0.0;
                         * driverProfit+=order.getEmployProfit()!=null?order.getEmployProfit():0.0;
                         * orderFinishedCouponMoney_this
                         * +=order.getCouponMoney()!=null?order.getCouponMoney():0.0; }
                         */
                        if ((order.getStatus().equals(4) || order.getStatus().equals(3)
                                || order.getStatus().equals(2) || order.getStatus().equals(1))
                                && companyId.equals(order.getEmployCompanyId())) {
                            runOrderNumber++;
                        }
                        if (order.getStatus().equals(0) && order.getCompanyId().equals(companyId)) {
                            runOrderNumber++;
                        }
                        // 外派订单
                        /*
                         * if(order.getStatus()==5 && order.getCompanyId()!=order.getEmployCompanyId()){
                         * otherOrderNumber++;
                         * otherOrderRealCash+=order.getRealPay()!=null?order.getRealPay():0.0;
                         * otherCompanyProfit+=order.getCompanyProfit()!=null?order.getCompanyProfit():0.0;
                         * otherDriverProfit=order.getEmployProfit()!=null?order.getEmployProfit():0.0;
                         * orderFinishedCouponMoney_getout
                         * +=order.getCouponMoney()!=null?order.getCouponMoney():0.0; }
                         */
                        if ((order.getStatus().equals(4) || order.getStatus().equals(3)
                                || order.getStatus().equals(2) || order.getStatus().equals(1))
                                && !companyId.equals(order.getEmployCompanyId())) {
                            runOtherOrderNumber++;
                        }
                        // 销单订单累加
                        if (order.getStatus().equals(6)) {
                            cancelOrderNumber++;
                        }
                    } else { // 调入订单
                        /*
                         * if(order.getStatus()==5 && companyId==order.getEmployCompanyId()){ inOrderNumber++;
                         * inOrderRealCash+=order.getRealPay()!=null?order.getRealPay():0.0;
                         * inCompanyProfit+=order.getCompanyProfit()!=null?order.getCompanyProfit():0.0;
                         * inDriverProfit+=order.getEmployProfit()!=null?order.getEmployProfit():0.0;
                         * orderFinishedCouponMoney_comein
                         * +=order.getCouponMoney()!=null?order.getCouponMoney():0.0; }
                         */
                        if ((order.getStatus().equals(4) || order.getStatus().equals(3)
                                || order.getStatus().equals(2) || order.getStatus().equals(1))
                                && companyId.equals(order.getEmployCompanyId())) {
                            inRunOrderNumber++;
                        }

                    }

                }
            }
            if (maincompany) {
                totalAmount = (list != null ? list.size() : 0) + (list2 != null ? list2.size() : 0);
                if (list2 != null && list2.size() != 0) {
                    for (Order order : list2) {
                        totalGuoluMoney += (order.getGuoluMoney() != null ? order.getGuoluMoney() : 0.0);
                        totalRealCash += (order.getRealPay() != null ? order.getRealPay() : 0.0);
                        totalCompanyProfit +=
                                (order.getCompanyProfit() != null ? order.getCompanyProfit() : 0.0);
                        totalDriverProfit += (order.getEmployProfit() != null ? order.getEmployProfit() : 0.0);
                        totalPayMoney +=
                                ((order.getRealPay() != null ? order.getRealPay() : 0.0) - (order.getCouponMoney()
                                        != null ? order
                                        .getCouponMoney() : 0.0));
                    }
                }
            }
            map.put("totalGuoluMoney", totalGuoluMoney);
            map.put("totalAmount", totalAmount);
            map.put("totalCancelAmount", totalCancelAmount);
            map.put("totalRealCash", totalRealCash);
            map.put("totalPayMoney", totalPayMoney);
            map.put("totalCompanyProfit", totalCompanyProfit);
            map.put("totalDriverProfit", totalDriverProfit);
            map.put("orderNumber", orderNumber);
            map.put("runOrderNumber", runOrderNumber);
            map.put("otherOrderNumber", otherOrderNumber);
            map.put("runOtherOrderNumber", runOtherOrderNumber);
            map.put("cancelOrderNumber", cancelOrderNumber);
            map.put("inOrderNumber", inOrderNumber);
            map.put("inRunOrderNumber", inRunOrderNumber);
            int sumOrderNumber = 0;// 合计订单数量
            sumOrderNumber =
                    orderNumber + runOrderNumber + otherOrderNumber + runOtherOrderNumber + cancelOrderNumber
                            + inOrderNumber + inRunOrderNumber;

            map.put("sumOrderNumber", sumOrderNumber);
            map.put("orderRealCash", orderRealCash);
            map.put("otherOrderRealCash", otherOrderRealCash);
            map.put("inOrderRealCash", inOrderRealCash);
            Double sumOrderRealCash = 0.0;// 合计订单金额
            sumOrderRealCash = orderRealCash + otherOrderRealCash + inOrderRealCash;

            map.put("sumOrderRealCash", sumOrderRealCash);

            map.put("companyProfit", companyProfit);
            map.put("otherCompanyProfit", otherCompanyProfit);
            map.put("inCompanyProfit", inCompanyProfit);
            Double sumCompanyProfit = 0.0;// 合计公司收入
            sumCompanyProfit = companyProfit + otherCompanyProfit + inCompanyProfit;

            map.put("sumCompanyProfit", sumCompanyProfit);

            map.put("driverProfit", driverProfit);
            map.put("otherDriverProfit", otherDriverProfit);
            map.put("inDriverProfit", inDriverProfit);
            Double sumDriverProfit = 0.0;// 合计司机收入
            sumDriverProfit = driverProfit + otherDriverProfit + inDriverProfit;
            map.put("sumDriverProfit", sumDriverProfit);
            Double totalCouponMoney = 0.0; // 合计优惠券金额
            totalCouponMoney =
                    orderFinishedCouponMoneyThis + orderFinishedCouponMoneyGetout
                            + orderFinishedCouponMoneyComein;
            map.put("totalCouponMoney", totalCouponMoney);
            map.put("orderTotalCouponMoney", totalCouponMoney);
            map.put("orderFinishedCouponMoney_this", orderFinishedCouponMoneyThis);
            map.put("orderFinishedCouponMoney_getout", orderFinishedCouponMoneyGetout);
            map.put("orderFinishedCouponMoney_comein", orderFinishedCouponMoneyComein);
            return map;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return map;
    }

    @Override
    public void updateRealMoney(Long orderId, Double couponMoney, Double cashMoney, Double signMoney,
                                Double balanceMoney, Double alipayMoney, Double weixinMoney, String operator, String content,
                                String appKey) {
        Order order = orderService.findByIdAndAppKey(orderId, appKey);
        order.setUpdated(new Date());
        OrderStatus status = new OrderStatus();
        status.setOrderId(order.getId());
        status.setOrderNo(order.getOrderNo());
        status.setStatus(5);
        status.setOperator(operator);
        status.setMemo("管理员【" + operator + "】" + "修改订单金额" + "原金额为" + order.getRealPay() + "元,修改后金额为:"
                + cashMoney + "元,修改原因:" + content);
        orderStatusService.insert(status);
        order.setRealPay(cashMoney);
        order.setCashMoney(cashMoney);
        if (couponMoney != null) {
            order.setCouponMoney(couponMoney);
        }
        if (signMoney != null) {
            order.setSignMoney(signMoney);
        }
        if (balanceMoney != null) {
            order.setBalanceMoney(balanceMoney);
        }
        if (alipayMoney != null) {
            order.setAlipayMoney(alipayMoney);
        }
        if (weixinMoney != null) {
            order.setWeixinMoney(weixinMoney);
        }
        orderService.updateIngoreNull(order);
    }

    @Override
    public DataGrid<Order> queryFinishOrderByEmployId(Long employId, Long start, Long end,
                                                      Integer page, Integer rows, String appKey) {
        DataGrid<Order> dataGrid = new DataGrid<Order>();
        List<Order> list = new ArrayList<Order>();

        list = orderService.queryFinishOrderByEmployId(employId, start, end, page, rows, appKey);

        Long count = orderService.countFinishOrderByEmployId(employId, start, end, appKey);

        dataGrid.setRows(list);

        dataGrid.setTotal(count);

        return dataGrid;
    }

    @Override
    public Long countByPassengerId(Long passengerId, String appKey) {
        return orderService.countByPassengerId(passengerId, appKey);
    }

    @Override
    public Long countRunning(Long passengerId, String appKey) {
        return orderService.countRunning(passengerId, appKey);
    }

    @Override
    public Long countSeats(Long employId, String appKey) {
        List<Order> orders = orderService.selectActivedByEmploy(employId, appKey);
        long seats = 0;
        if (!CollectionUtils.isEmpty(orders)) {
            for (Order order : orders) {
                if (!order.isYuyue()) {
                    seats += (order.getPeopleNumber() == null ? 0 : order.getPeopleNumber());
                }
            }
        }
        return seats;
    }

    @Override
    public List<Order> findNewOrder(Long companyId, String appKey) {

        return orderService.selectNewOrder(companyId, appKey);

    }

    @Override
    public List<Order> findActivedOrder(Long employId, String appKey) {
        return orderService.selectActivedByEmploy(employId, appKey);
    }

    /**
     * 取消订单.
     *
     * @param orderId  订单主键
     * @param operator 操作者
     * @param cause    原由
     * @param appKey   appKey
     */
    public void cancelOrder(Long orderId, String operator, String cause, String appKey) {
        try {
            Order order = orderService.findByIdAndAppKey(orderId, appKey);
            if (null != order.getEmployId()) {
                Car car = carService.findByEmploy(order.getEmployId(), appKey);
                if (car != null) {
                    car.setStatus(Car.CAR_FREE);
                    carService.update(car);
                }
            }
            OrderStatus orderStatus = new OrderStatus();
            orderStatus.setOrderId(orderId);
            orderStatus.setOrderNo(order.getOrderNo());
            orderStatus.setStatus(6);
            orderStatus.setOperator(operator);
            if (order.getStatus() == Order.ORDER_STATUS_JIEDAN) {
                orderStatus.setMemo("管理员【" + operator + "】" + "后台强制取消订单");
            } else {
                orderStatus.setMemo("管理员【" + operator + "】" + "后台取消订单");
            }
            order.setStatus(6);
            order.setIsClosed(true);
            order.setCancelCause(cause);
            orderStatusService.insert(orderStatus);

            orderService.updateIngoreNull(order);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public List<Order> findRunOrderByEmployId(Long employId, Boolean treatment, String appKey) {
        return orderService.findRunOrderByEmployId(employId, treatment, appKey);
    }

    @Override
    public Long queryRunOrder(Long passengerId, String appKey) {
        return orderService.queryRunOrder(passengerId, appKey);
    }

    @Override
    public List<Order> findHastenOrderAppKey(String appKey) {
        return orderService.findHastenOrder(appKey);
    }

    @Override
    public boolean isReceiveAnOrder(Integer orderType, Long employId, Long peopleNumber,
                                    String appKey) {
        Car car = carService.findByEmploy(employId, appKey);
        if (car == null) {
            return false;
        }
        List<Order> orders = this.findRunOrderByEmployId(employId, null, appKey);
        if (Order.TYPE_PINCHE.equals(orderType)) {
            Long seats = this.countSeats(employId, appKey);
            if (peopleNumber + seats > car.getRidepeopleNumber()) {
                return false;
            }
            boolean flag = false;
            for (Order temp : orders) {
                if (Order.TYPE_BAOCHE.equals(temp.getOrderType())) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                return false;
            }
        } else if (Order.TYPE_BAOCHE.equals(orderType)) {

            boolean flag = false;
            for (Order temp : orders) {
                if (Order.TYPE_BAOCHE.equals(temp.getOrderType())
                        || temp.getOrderType().equals(Order.TYPE_PINCHE)
                        || temp.getOrderType().equals(Order.TYPE_JIHUO)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                return false;
            }
        } else if (Order.TYPE_JIHUO.equals(orderType)) {
            boolean flag = false;
            for (Order temp : orders) {
                if (Order.ORDER_STATUS_ZHIXING.equals(temp.getStatus())
                        || Order.TYPE_BAOCHE.equals(temp.getOrderType())) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                return false;
            }
            flag = false;
            for (Order temp : orders) {
                if (Order.TYPE_BAOCHE.equals(temp.getOrderType())) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                return false;
            }
        }

        return true;
    }

    @Override
    public List<Order> findUnexecutedByEmployId(Long employId, String appKey) {

        return orderService.findUnexecutedByEmployId(employId, appKey);
    }

    @Override
    public DataGrid<Order> findOrderByPassenger(Long passengerId, Integer page, Integer rows,
                                                String appKey) {
        Integer offset = null;
        if (page != null && rows != null) {
            offset = (page - 1) * rows;
        }
        List<Order> list = orderService.findOrderByPassenger(passengerId, offset, rows, appKey);
        for (Order order : list) {
            order.setOrderReview(orderReviewService.findByOrderIdAndAppKey(order.getId(), appKey));
        }
        Long count = orderService.countOrderByPassengerId(passengerId, appKey);
        DataGrid<Order> data = new DataGrid<Order>();
        data.setRows(list);
        data.setTotal(count);
        return data;
    }

    @Override
    public List<Order> findByWork(Long employId, String appKey, String status) {
        List<Order> orders = null;
        List<Integer> statusList = new ArrayList<Integer>();
        if ("pai".equals(status)) {
            statusList.add(1);
        } else if ("waitorrun".equals(status)) {
            statusList.add(2);
            statusList.add(3);
            statusList.add(4);
        } else if ("finish".equals(status)) {
            statusList.add(5);
        }

        orders = orderService.findByWork(employId, statusList, appKey);
        return orders;
    }

    @Override
    public List<Order> findRunOrderByLineId(Long lineId, String appKey) {
        return orderService.findRunOrderByLineId(lineId, appKey);
    }

    @Override
    public List<Order> findRunOrderByCarId(Long carId, String appKey) {
        return orderService.findRunOrderByCarId(carId, appKey);
    }

    @Override
    public List<Order> findJiedanOrderByEmployId(Long employId, String appKey) {
        return orderService.findJiedanOrderByEmployId(employId, appKey);
    }

    @Override
    public Long jiedanCountSeats(Long employId, String appKey) {
        List<Order> orders = orderService.findJiedanOrderByEmployId(employId, appKey);
        long seats = 0;
        if (!CollectionUtils.isEmpty(orders)) {
            for (Order order : orders) {
                if (!order.isYuyue()) {
                    seats += (order.getPeopleNumber() == null ? 0 : order.getPeopleNumber());
                }
            }
        }
        return seats;
    }

    @Override
    public Boolean prepare(Long orderId, String appKey) {
        Boolean bool = false;
        int update = orderService.prepare(orderId, appKey);
        if (update == 1) {
            bool = true;
        }
        return bool;
    }

    @Override
    public Long driverOrderDetailCount(Long employId, Date startDate, Date endDate, String appKey) {
        return orderService.driverOrderDetailCount(employId, startDate, endDate, appKey);
    }

    @Override
    public int updateAnonymousNumber(Long orderId, String anonymousNumber, String appKey) {
        return orderService.updateAnonymousNumber(orderId, appKey, anonymousNumber);
    }

}
